package com.garbuz.svnadmin;

import com.garbuz.svnadmin.data.Group;
import com.garbuz.svnadmin.data.Permission;
import com.garbuz.svnadmin.data.ProcessTO;
import com.garbuz.svnadmin.data.Repo;
import com.garbuz.svnadmin.data.RepoResponse;
import com.garbuz.svnadmin.data.User;
import com.garbuz.svnadmin.data.UserResponse;
import com.garbuz.svnadmin.model.SvnModel;
import com.garbuz.svnadmin.model.SvnModelReader;
import com.garbuz.svnadmin.model.SvnModelWriter;
import common.serialization.Serializer;
import common.system.ProcessManager;

import javax.servlet.ServletContext;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;

public class AdminApplication
{

	static private AdminApplication instance;

	static public AdminApplication getInstance()
	{
		return instance;
	}

	static void createInstance(ServletContext context) throws Exception
	{
		if (instance != null)
			throw new Exception("Instance is already created");

		instance = new AdminApplication();
		instance.initialize(context);

	}

	private ApplicationConfig config;
	private ProcessManager processManager;
	private String rootPath;

	private void initialize(ServletContext context) throws IOException
	{
		rootPath = context.getRealPath("/WEB-INF");
		processManager = new ProcessManager();
		initSerializer();
		readProperties();
	}

	private void initSerializer()
	{
		Serializer.registerType(User.class.getCanonicalName());
		Serializer.registerType(Group.class.getCanonicalName());
		Serializer.registerType(Repo.class.getCanonicalName());
		Serializer.registerType(Permission.class.getCanonicalName());
		Serializer.registerType(UserResponse.class.getCanonicalName());
		Serializer.registerType(RepoResponse.class.getCanonicalName());
		Serializer.registerType(ProcessTO.class.getCanonicalName());
	}

	private void readProperties() throws IOException
	{
		String fileName = rootPath.concat("/application.properties");
		Properties properties = new Properties();
		properties.load(new FileReader(fileName));
		config = new ApplicationConfig(properties);
	}

	public SvnModel readModel() throws Exception
	{
		return new SvnModelReader().read(
				config.getSvnRootPath(),
				config.getPasswordsFile(),
				config.getAuthzFile());
	}

	public void writeModel(SvnModel model) throws Exception
	{
		new SvnModelWriter(model).write(
				config.getPasswordsFile(),
				config.getAuthzFile());
	}

	public ApplicationConfig getConfig()
	{
		return config;
	}

	public ProcessManager getProcessManager()
	{
		return processManager;
	}

	public String getRootPath()
	{
		return rootPath;
	}
}
